﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SettingsPage.xaml.cs" company="Mar3ek">
//   This code is licensed under the Mozilla Public License 2.0.
//   You can find the full license text at the following address:
//   https://winkee.codeplex.com/license
// </copyright>
// <summary>
//   An empty page that can be used on its own or navigated to within a Frame.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace WinKee.Pages
{
    using System;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using System.Windows.Input;

    using Windows.Storage;
    using Windows.Storage.AccessCache;
    using Windows.UI.Popups;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Navigation;

    using WinKee.Common;
    using WinKee.Dialogs;

    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class SettingsPage : INotifyPropertyChanged
    {
        /// <summary>
        /// Indicates whether the application requires resume password.
        /// </summary>
        private bool requiresPinCode;

        /// <summary>
        /// Stores the current value for the DisplayUsernameInList setting.
        /// </summary>
        private bool displayUsernameInList;

        private bool useColorsInList;

        private bool useMru;

        /// <summary>
        /// Initializes a new instance of the <see cref="SettingsPage"/> class.
        /// </summary>
        public SettingsPage()
        {
            this.InitializeComponent();

            this.NavigationHelper = new NavigationHelper(this);
            var localSettings = ApplicationData.Current.LocalSettings;
            var pinSetting = localSettings.ReadSetting(Definitions.PinSettingKey, false);

            this.RequiresPinCode = pinSetting;
            this.RequiresPinToggleSwitch.IsOn = pinSetting;

            this.displayUsernameInList = localSettings.ReadSetting(Definitions.DisplayUsernamesInListSettingKey, false);
            this.DisplayUsernameInListToggleSwitch.IsOn = this.displayUsernameInList;

            this.useColorsInList = localSettings.ReadSetting(Definitions.UseEntryColorsSettingKey, false);
            this.UseColorsInListToggleSwitch.IsOn = this.useColorsInList;

            this.useMru = localSettings.ReadSetting(Definitions.UseMRUSettingKey, false);
            this.UseMRUToggleSwitch.IsOn = this.useMru;

            this.ClearMRUCommand = new RelayCommand(this.ClearMRUAction);
        }

        private void ClearMRUAction()
        {
            StorageApplicationPermissions.MostRecentlyUsedList.Clear();
        }

        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
        /// </summary>
        public NavigationHelper NavigationHelper { get; private set; }

        /// <summary>
        /// Gets a value indicating whether the application requires resume password.
        /// </summary>
        public bool RequiresPinCode
        {
            get
            {
                return this.requiresPinCode;
            }

            private set
            {
                this.requiresPinCode = value;
                this.OnPropertyChanged();
            }
        }

        public ICommand ClearMRUCommand { get; private set; }

        #region NavigationHelper registration

        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.NavigationHelper.OnNavigatedTo(e);
        }

        /// <summary>
        /// Handles the OnNavigatedTo event.
        /// </summary>
        /// <param name="e">
        /// The event arguments.
        /// </param>
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.NavigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        /// <summary>
        /// Raises the PropertyChanged event.
        /// </summary>
        /// <param name="propertyName">
        /// The property name.
        /// </param>
        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Handles the Toggled event.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The event arguments.
        /// </param>
        private async void RequiresPinToggled(object sender, RoutedEventArgs e)
        {
            if (this.RequiresPinCode == this.RequiresPinToggleSwitch.IsOn)
            {
                return;
            }

            if (this.RequiresPinToggleSwitch.IsOn)
            {
                // creating a NEW password
                var dialog = new NewPinDialog();
                var result = await dialog.ShowAsync();

                if (result != ContentDialogResult.Primary || string.IsNullOrEmpty(dialog.Password))
                {
                    this.RequiresPinToggleSwitch.IsOn = false;
                    return;
                }

                ApplicationData.Current.LocalSettings.Values[Definitions.PinSettingKey] = true;
                ApplicationData.Current.LocalSettings.Values[Definitions.PinContentKey] = PasswordSecurity.ProtectAppPassword(dialog.Password);

                this.RequiresPinCode = true;
            }
            else
            {
                // removing an existing password

                // new code: only display confirmation
                var dialog = new MessageDialog(
                    "Are you sure you want to remove the application password?",
                    "WinKee - remove app password");

                dialog.Commands.Add(
                    new UICommand(
                        "yes",
                        command =>
                            {
                                ApplicationData.Current.LocalSettings.Values[Definitions.PinSettingKey] = false;
                                ApplicationData.Current.LocalSettings.Values.Remove(Definitions.PinContentKey);
                                this.RequiresPinCode = false;
                            }));

                dialog.Commands.Add(
                    new UICommand(
                        "no",
                        command =>
                            {
                                this.RequiresPinToggleSwitch.IsOn = true;
                            }));
                await dialog.ShowAsync();
            }
        }

        /// <summary>
        /// Handles the Toggled event.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The event arguments.
        /// </param>
        private void DisplayUsernameInListToggleSwitch_OnToggled(object sender, RoutedEventArgs e)
        {
            if (this.DisplayUsernameInListToggleSwitch.IsOn == this.displayUsernameInList)
            {
                return;
            }

            ApplicationData.Current.LocalSettings.Values[Definitions.DisplayUsernamesInListSettingKey] =
                this.DisplayUsernameInListToggleSwitch.IsOn;
            this.displayUsernameInList = this.DisplayUsernameInListToggleSwitch.IsOn;
        }

        private void UseColorsInListToggleSwitch_OnToggled(object sender, RoutedEventArgs e)
        {
            if (this.UseColorsInListToggleSwitch.IsOn == this.useColorsInList)
            {
                return;
            }

            ApplicationData.Current.LocalSettings.Values[Definitions.UseEntryColorsSettingKey] =
                this.UseColorsInListToggleSwitch.IsOn;
            this.useColorsInList = this.UseColorsInListToggleSwitch.IsOn;
        }

        private void UseMRUToggleSwitch_OnToggled(object sender, RoutedEventArgs e)
        {
            if (this.UseMRUToggleSwitch.IsOn == this.useMru)
            {
                return;
            }

            if (!this.UseMRUToggleSwitch.IsOn)
            {
                StorageApplicationPermissions.MostRecentlyUsedList.Clear();
            }

            ApplicationData.Current.LocalSettings.Values[Definitions.UseMRUSettingKey] = this.UseMRUToggleSwitch.IsOn;
            this.useMru = this.UseMRUToggleSwitch.IsOn;
        }
    }
}
